import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// 引入⬇️
import postCssPxToRem from 'postcss-pxtorem'
import autoprefixer from 'autoprefixer'

import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
// import OptimizationPersist from 'vite-plugin-optimize-persist'
// import PkgConfig from 'vite-plugin-package-config'
// import { dirResolver, DirResolverHelper } from 'vite-auto-import-resolvers'
import { createStyleImportPlugin, ElementPlusResolve } from 'vite-plugin-style-import'

// https://vitejs.dev/config/
export default defineConfig({
  base: './',
  build: {
    chunkSizeWarningLimit: 10500,
    rollupOptions: {
      output: {
        manualChunks(id) {
          if (id.includes('node_modules')) {
            return id.toString().split('node_modules/')[1].split('/')[0].toString()
          }
        }
      }
    }
  },

  plugins: [
    vue(),
    // DirResolverHelper(),
    //自动生成 预打包
    // PkgConfig(),
    // OptimizationPersist(),
    // 自动导入组件
    AutoImport({
      resolvers: [ElementPlusResolver()]
      // resolvers: [dirResolver()]
    }),
    Components({
      resolvers: [ElementPlusResolver()]
    }),
    // 自定导入样式文件
    createStyleImportPlugin({
      resolves: [ElementPlusResolve()],
      libs: [
        {
          libraryName: 'element-plus',
          esModule: true,
          resolveStyle: (name) => {
            return `element-plus/theme-chalk/${name}.css`
          }
        }
      ]
    })
  ],
  server: {
    port: 3004,
    host: '0.0.0.0',
    open: true,
    proxy: {
      '/api': {
        target: 'http://111.198.29.34:18504/shandong_api',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, '')
      }
    }
  },

  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  },
  css: {
    postcss: {
      plugins: [
        postCssPxToRem({
          // 换算基数，设计稿宽度或者目前正常分辨率的1/24
          rootValue: 80,
          // 匹配CSS中的属性，* 代表启用所有属性
          propList: ['*']
        }),
        autoprefixer({
          // 自动添加前缀
          overrideBrowserslist: [
            'Android 4.1',
            'iOS 7.1',
            'Chrome > 31',
            'ff > 31',
            'ie >= 8'
            //'last 2 versions', // 所有主流浏览器最近2个版本
          ],
          grid: true
        })
      ]
    }
  }
})
